﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using l1cs.server.model.Instance;
using l1cs.server.serverpackets;
using l1cs.server.model;

namespace l1cs.server
{
    class Announcements
    {
        private static Logger _log = Logger.getLogger( typeof( Announcements ).FullName );

        private static Announcements _instance;

        private List<String> _announcements = new List<String>();

        public static Announcements getInstance()
        {
            if ( _instance == null )
            {
                _instance = new Announcements();
            }

            return _instance;
        }

        private Announcements()
        {
            _announcements.Clear();
            String file = "data/announcements.txt";
            if ( System.IO.File.Exists( file ) )
            {
                readFromDisk( file );
            }
            else
            {
                _log.config( "data/announcements.txt doesn't exist" );
            }
        }

        public List<String> getAnnouncements()
        {
            return _announcements;
        }

        public void showAnnouncements( L1PcInstance showTo )
        {
            foreach ( String msg in _announcements )
            {
                showTo.sendPackets( new S_SystemMessage( msg ) );
            }
        }

        private void readFromDisk( String file )
        {
            FileStream fin = new FileStream( file, FileMode.Open );
            int i = 0;
            using ( StreamReader sr = new StreamReader( fin, Encoding.GetEncoding( "Shift_JIS" ) ) )
            {
                String line = "";
                while ( ( line = sr.ReadLine() ) != null )
                {
                    _announcements.Add( line );
                    i++;
                }
            }
            _log.config( "告知事項 " + i + "件ロード" );
        }

        private void saveToDisk()
        {
            using ( StreamWriter sw = new StreamWriter( "data/announcements.txt" ) )
            {
                foreach ( String msg in _announcements )
                {
                    sw.WriteLine( msg );
                }
            }
        }

        public void announceToAll( String msg )
        {
            L1World.getInstance().broadcastServerMessage( msg );
        }
    }
}
